package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.Conver_MD5;
import com.nikmesoft.android.referendumfriend.models.user_settings;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.service.SettingHanler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class Setting extends BaseActivity{

	private EditText newpass;
	private EditText confirm;
	private EditText oldpass;
	private ProgressDialog dialog;
	private WSLoader loader;
	private user_settings user_set;
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
       
        newpass=(EditText) findViewById(R.id.newpass);
        oldpass=(EditText) findViewById(R.id.oldpass);
        confirm=(EditText) findViewById(R.id.confirm);
        dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
		user_set=new user_settings();
	}
	public void callSave(View v){
		String st1=newpass.getText().toString();
		String st2=confirm.getText().toString();
		String st3=oldpass.getText().toString();
		if (st1.equals("") || st2.equals("") || st3.equals("")) 
				{CommonUtil.toastNotify(this,"You must complete all fileds!");
				return;
				}
		if (!st1.equals(st2))
		 {
			AlertDialog.Builder alert=new AlertDialog.Builder(Setting.this);
			alert.setTitle("Waring!");
			alert.setMessage("Confirm password must be the same new password!");
			alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					
				}
			});
			alert.show();
			return;
		 }
		if (!LoginHandler.result.getPass().equals(st3)) {CommonUtil.toastNotify(this,"Old password wrong!" ); return;}
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			String id=String.valueOf(LoginHandler.result.getId());
			loader.execute(id,st1);
		}
		
	}
	public void callBack(View v){
		finish();
	}
	
	private String callWS(String id,String pass			) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				
				+ "<changePassword soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
		        + "<ChangePasswordRequest xsi:type=\"rdf:ChangePasswordRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
		         
		        +  "<id xsi:type=\"xsd:int\">"+id+"</id>"
		        +  "<newpassword xsi:type=\"xsd:string\">"+pass+"</newpassword>"
		        + "</ChangePasswordRequest>"
		        + "</changePassword>"
		        + "</soapenv:Body>"
		        + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private user_settings xmlParser(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			SettingHanler handler = new SettingHanler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private class WSLoader extends AsyncTask<String, Integer, user_settings> {

		@Override
		protected user_settings doInBackground(String... params) {
			return xmlParser(callWS(params[0], Conver_MD5.md5Digest(params[1])));
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(user_settings result) {
			super.onPostExecute(result);
			
			if (result.getError()!= null) toad(result.getError().getErrorMsg());
			else 
				{
				
				LoginHandler.result.setPass(newpass.getText().toString().trim());
				finish();
				}
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}
	public void toad(String str){
		CommonUtil.toastNotify(this,str);
	}
}

